$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    console.log('detail Ready');
    const mstform = $NG.getCmpApi('p_form_htzlyj_m');
    const dgrid = $NG.getCmpApi('p_form_htzlyj_d1');
    const toolbar = $NG.getCmpApi("toolbar_top")
    // toolbar.insert({
    //     id: "myadd",
    //     text: "debug测试",
    //     iconCls: "icon-New"
    // });
    useClick(() => {
        importAttachment()
    }, 'myadd')
    const config = {
        u_yjwj_bak: [],
        attachment_detali: []
    }
    if(page.oType == 'edit' || page.oType == 'add'){
        importAttachment()
    }
    // 定义文件类型映射关系
    const FILE_TYPE_MAP = {
        "01": "全选",
        "02": "招标文件",
        "03": "投标文件",
        "04": "开标记录",
        "05": "中标公示截图",
        "06": "中标通知书",
        "07": "合同"
    };

    // 存储原始数据备份
    let isFiltering = false; // 标记是否正在执行过滤操作

    // 在网格渲染后备份原始数据
    originalGridData = dgrid.getRows().map(row => ({ ...row }));
    console.log('原始数据已备份', originalGridData);
    // useAction('afterRender')(() => {
    //     // 备份原始数据

    //     // 页面加载时初始化过滤
    //     const initialValues = mstform.getItem('u_yjwj').getValue() || [];
    //     filterGridData(initialValues);
    // }, 'p_form_htzlyj_d1');

    // 监听u_yjwj多选框变化
    useValuesChange(({ args }) => {
        let selectedValues = mstform.getItem('u_yjwj').getValue() || [];
        if (JSON.stringify(selectedValues) == JSON.stringify(config.u_yjwj_bak)) {
            return
        }
        console.log('多选框值变化:', selectedValues);
        if (selectedValues.includes('01')) {
            if (config.u_yjwj_bak.includes('01')) {
                const temp = selectedValues.filter(el => {
                    if (el != '01') {
                        return true
                    } else {
                        return false
                    }
                })
                mstform.getItem('u_yjwj').setValue([...temp])
                config.u_yjwj_bak = [...temp]
            } else {
                mstform.getItem('u_yjwj').setValue(['01', '02', '03', '04', '05', '06', '07'])
                config.u_yjwj_bak = ['01', '02', '03', '04', '05', '06', '07']
            }

        } else {
            // 取消全选
            if (config.u_yjwj_bak.includes('01')) {
                mstform.getItem('u_yjwj').setValue([])
                config.u_yjwj_bak = []
            } else {
                if (selectedValues.join(',') == ['02', '03', '04', '05', '06', '07'].join(',')) {
                    mstform.getItem('u_yjwj').setValue(['01', '02', '03', '04', '05', '06', '07'])
                    selectedValues = ['01', '02', '03', '04', '05', '06', '07']
                }
            }
            config.u_yjwj_bak = [...selectedValues]
        }

        // 改变明细
        let temp = []
        if (config.u_yjwj_bak.includes("01")) {
            temp = [...config.attachment_detali]
        } else {
            config.u_yjwj_bak.forEach(item => {
                const ty = config.attachment_detali.filter(it => {
                    if (it.u_fjlx == FILE_TYPE_MAP[item]) {
                        return true
                    }
                    return false
                })
                temp.push(...ty)
            })
        }
        console.log(temp)
        dgrid.clearRows().then(() => {
            dgrid.addRows(temp)
        })

    }, "p_form_htzlyj_m.u_yjwj");

    useValuesChange(({ args }) => {
        console.log(`args`, args);
        mstform.getItem("u_htbh").setValue(args[0].u_htmc.origin.bill_no)
        importAttachment()
        getHtps()
    }, "p_form_htzlyj_m.u_htmc")
    // 确保在数据变化时更新备份
    useUpdateRows(({ args }) => {
    }, 'p_form_htzlyj_d1');

    // 获取合同信息
    function getHtps() {
        const phid = mstform.getItem("u_htmc").getValue()
        if (!phid) return
        $NG.execServer("SELECT", { sql: `SELECT m.phid_pc,project.bill_name phid_pc_exname,m.user_xmmc,m.cnt_sum_fc,m.user_htqdsj FROM pcm3_cnt_checkup m left join project_table project on project.phid = m.phid_pc where m.phid = '${phid}'` }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_htzlyj_m.setProps({
                    phid_pc: {
                        label: datas.phid_pc_exname,
                        value: datas.phid_pc
                    },
                    // u_bdmc:datas.,
                    u_xmmc: datas.user_xmmc,
                    u_htje: datas.cnt_sum_fc,
                    u_htqdsj: datas.user_htqdsj
                })
            })
        })
    }


    async function importAttachment() {
        // return false;
        const fidsps_data = []
        let fidtbqk_data = []
        const mohid = mstform.getItem("u_htmc").getValue()
        if(!mohid) return 
        const ress = await $NG.execServer("SELECT", { sql: `select b.user_lyid phid from pcm3_cnt_checkup m  left join project_table b on b.phid = m.phid_pc where m.phid = '${mohid}'` })
        if (ress.count == 0) return
        console.log(ress, 99999, ress.data)
        const phid = JSON.parse(ress.data)[0].extendObjects.phid
        if (!phid) return
        // %@U2FsdGVkX1+FZb4IuhL21sue😀q+M7LzwStVVwvJP+HfPqlT3naG0agUFDVNXPlHxCnrgFQ2pREygQ+MGL+RK3Kw+bIMFv6gXexkOK82NSRvi47+xyuLKIbupC1g2eP+Y&&0.0.5
        config.attachment_detali = []
        if(page.oType == 'add'){
            mstform.getItem("u_yjwj").setValue([])
        dgrid.clearRows()
        }
        // %@U2FsdGVkX1954B5E16BzGE5Uem23peb7DMP2nxV😀mYddDCgZGu😀VJOBZ87PCFamf5xz+YKReQdxLPkvZIR8gMg==&&0.0.5
        // $NG.execServer("getTbqkzjAttachmentInfo", { phid }, async (res) => {
        //     if (res.count == 0) return
        //     const datas = JSON.parse(res.data)[0].extendObjects
        //     if (datas) {

        //     }
        // })
        // %@U2FsdGVkX18pTx8gQ/HMuX2sgI9RbG7ugDhkXdahoBwZdO/6V9fohXurYdPde6+5zmeJdRXdMwl8z8tsZyOgl😀==&&0.0.5
        // %@U2FsdGVkX1/Br62XRknLF7GHoBNsclro5hGRuq26lGI=&&0.0.5
        // %@U2FsdGVkX1/qIrGeVqG+eK7😀F/ikp53sHinazHKiP8BMGUJsP1b+sWiJgk/Hdgu2/3vXe/1Hj7xwHUq75Xeh0Ds8HGprCRh16vc1GGclNBv5pplVFrLeqPq/yWYVM/X8zzvYfbdUzZGBskYWL3Yb/FRx639rpdhR5cGoVjvc6PU4g8YDggJOaXp5J8MyFxVu&&0.0.5
        const resps = await $NG.execServer("SELECT", { sql: `select asr_fid,typeid from attachment_record where asr_table = 'pcm3_cnt_checkup' and asr_code=${mohid}` })
        if (resps.count > 0) {
            const datas = JSON.parse(resps.data)
            console.log(`resps`, resps, datas);
            // %@U2FsdGVkX1+XLEJVH0GrvHeJtYnF/1TFNOtpaYCDDC😀mPrmf8zmOCwHYm8bE3hiYGQd/lDIT3R9t2wW3WTnVbg==&&0.0.5
            let zbtzs = datas.filter((item) => {
                const it = item.extendObjects
                if (it.typeid == 6870000000000053) { // 中标通知书
                    return true
                } else {
                    return false
                }
            })
            let ht = datas.filter((item) => {
                const it = item.extendObjects
                if (it.typeid == 6870000000000054) { // 合同
                    return true
                } else {
                    return false
                }
            })
            if (zbtzs.length > 0) {
                fidsps_data.push(zbtzs[0].extendObjects.asr_fid)
            }
            if (ht.length > 0) {
                fidsps_data.push(ht[0].extendObjects.asr_fid)
            }
            // %@U2FsdGVkX1+jXalh04mwhM+5gYlY0wY+PoQG1lHC3lgvtbbv2Z3tHtYZnnPtkzwFt9iVuBvcGy4qSKiO8l1ax9jZJVqGz/wDQ😀kEv4aTx0U=&&0.0.5
        }

        const restbqk = await $NG.execServer("SELECT", { sql: `select asr_fid,typeid from attachment_record where asr_table = 'crm3_tend_analy' and asr_code=${phid}` })
        if (restbqk.count > 0) {
            const datas = JSON.parse(restbqk.data)
            console.log(`restbqk`, restbqk, datas);
            // %索引解释，招标文件 投标文件 开标记录 中标公示
            const arr = [false, false, false, false]
            datas.forEach(item => {
                switch (item.extendObjects.typeid) {
                    case 6870000000000023:
                        if (!arr[0]) {
                            arr[0] = item.extendObjects.asr_fid
                        }
                        break
                    case 6870000000000024:
                        if (!arr[1]) {
                            arr[1] = item.extendObjects.asr_fid
                        }
                        break;
                    case 6870000000000025:
                        if (!arr[2]) {
                            arr[2] = item.extendObjects.asr_fid
                        }
                        break;
                    case 6870000000000042:
                        if (!arr[3]) {
                            arr[3] = item.extendObjects.asr_fid
                        }
                        break;
                }
            })
            fidtbqk_data = [...arr]


            // %@U2FsdGVkX1+jXalh04mwhM+5gYlY0wY+PoQG1lHC3lgvtbbv2Z3tHtYZnnPtkzwFt9iVuBvcGy4qSKiO8l1ax9jZJVqGz/wDQ😀kEv4aTx0U=&&0.0.5
        }

        // %@U2FsdGVkX1+iMyYE/dv4eKg7EaPGBhTB0rduy😀y56U4uyNpNeCFRZxg/WqlHXZcewIL8Xf8OwlGwupcxhYt😀uQ==&&0.0.5
        // await $NG.execServer("getTbqkzj2AttachmentInfo", { fid }, async (res2) => {
        //     let fids = []
        //     if (res2.count == 0) return
        //     const attachments = JSON.parse(res2.data)[0].extendObjects
        //     fids.push(attachments.u_fj)
        //     fids.push(attachments.u_tbwj)
        //     fids.push(attachments.u_kbjl)
        //     fids.push(attachments.u_zbgsjt)
        //     console.log("fids", [...fids])
        //     // %@U2FsdGVkX183rFo8OuS/PF1TvP/BtXG3bJ80NMx0ts😀UKBlZxeuqrHvZu2XtvxW4p2WTq8dgRhrdF😀m9t03eI😀==&&0.0.5
        //     fids = fids.filter(it => {
        //         try {
        //             if (!it.split('@@')[1] || it.split('@@')[1] == '0') {
        //                 return false
        //             } else {
        //                 return true
        //             }
        //         } catch (e) {
        //             return false
        //         }
        //     })
        // %@U2FsdGVkX1/w9mO3zPNFfb/lYDmo4wQgZLIOta😀CM1qqMJV9KZ3PklDVHo/SL2Dg0T😀7Dx99GmbPHMO1zMGf4UWf9yF9W1bIWqJK202oVJ😀=&&0.0.5
        // fids = fids.map(el => el.split('@@')[0] || '无')
        // %@U2FsdGVkX1/bLYYL9t3aSHb/9hT4HkZ3nrp4/2😀OaLYEFqiKFHYG1pZv+BBb7x6Yk87iu😀XUGCWgq9guCxv2ib05W😀GohkrUJ4SOrEfBvwzSdY0vnw2C1Ee5CIVrRHNUJ74u+WM4xYOrsitY+dCb56rJP0ekqzwdK1kchOT0Jmc6ltJXs9Q/e9SLrSoyyuDfaXR😀jUDDb5H+ICwIi😀GOs😀==&&0.0.5
        window._catch_rows = []
        // for (let i = 0; i < fids.length; i++) {
        //     const asrId = fids[i]
        //     // TODO
        //     const su = await importAttachMentFile(asrId, i)
        //     console.log(`到循环了`, su);
        //     if (su) {
        //         fids[i] = false
        //     }
        // }

        for (let i = 0; i < fidtbqk_data.length; i++) {
            const asrId = fidtbqk_data[i]
            // TODO
            const su = await importAttachMentFile(asrId, i, true)
            console.log(`到循环了`, su);
            if (su) {
                fidtbqk_data[i] = false
            }
        }

        // %@U2FsdGVkX1+1vSIlkfz6N2aFWBt/9OqmRvWt2X1Zp😀XlIzeUxWpzyPQpKi8x8NJDDR5XmLpW2k8eSKag5NMz8w==&&0.0.5
        for (let i = 0; i < fidsps_data.length; i++) {
            const asrId = fidsps_data[i]
            // TODO
            const su = await importAttachMentFile(asrId, i == 0 ? 4 : 5, true)
            console.log(`到循环了`, su);
            if (su) {
                fidsps_data[i] = false
            }
        }
        // %@U2FsdGVkX18fyPFemc61kJ6C47ooXwq/D3oeTnN7LgSeHeEcGNlU9qoDm6vUl1vi&&0.0.5
        window._catch_fidTime = setInterval(() => {
            const temp = fidtbqk_data.filter((ip) => ip)
            const temp1 = fidsps_data.filter((ip) => ip)
            console.log(`temp,fidsps_data`, temp, temp1);
            if (temp.length == 0 && temp1.length == 0) {
                clearInterval(window._catch_fidTime)
                console.log(`添加的数据`, window._catch_rows);
                // dgrid.addRows(rows)
                config.attachment_detali = window._catch_rows
            }
        }, 1000)
        // })
    }

    // %@U2FsdGVkX1/tsLxSOJfmp983RYcrKqRPLzcHIxqHBLz+dxkYD//lMorJ😀1EUOJi52ZhCP0mucQ/j0OvPe7ul6z8JjdxeL0NTlJpTfDvLmE6jvaqyb5bNZdIYeWR+CUhD&&0.0.5
    // %@U2FsdGVkX19WOPxCxchpNd😀ChvtUxlhtMUKY/I0bRc9k8S6J3sPQwkwzV5bci4zn1GQqKDSfkFuHgGek2YRwtpDVGkL9dkynQ5Yl4DRCXuYOsWlSctWLz9CO158😀ZPU24dldPd4dZtz7qcxY9ahf4/Zj6q2it5rqgkxMEwhLmHHcg😀joL3VYYCUUrMd75/dQe3bTfJQqXK+f😀BtzRGyQhCMLsTHmIDjhi6lr/ciuYYR7Mxs2xfKoe7vyTLR0ncB2&&0.0.5
    async function importAttachMentFile(asrId, sort, oneFid) {
        // %@U2FsdGVkX1+PCn6pT+klJ+IJ44t5fENwjbpursRC2TcEiMOTj2fmB😀kD7bj43+NqizgjbLqR/nv8ZMruCYSq5😀==&&0.0.5
        if (oneFid) {
            const res = await $NG.execServer("SELECT", { sql: `select att.asr_fid, att.asr_name, att.asr_fill, att.asr_filldt, att.asr_fillname, att.asr_session_guid from attachment_record att where att.asr_fid = '${asrId}'` })
            console.log(`单一id`, res, asrId);
            if (res.count > 0) {
                const datas = JSON.parse(res.data)[0].extendObjects
                importFile(sort, datas)
            }
        }
        // %@U2FsdGVkX1+UrgicOi2Wp6hXBZ😀UEwSf0utBXNqUal+fzwNsTWq6bVkssFZdSN1g0PLbsjbDr4GSgdFQ😀L9iLphED6lZ3rvKsJ49qCBHp33MY4rlKmYyQFZfbxBmQIU2&&0.0.5
        await $NG.execServer("getAttachnentByAseSession", { asrId }, async (result) => {
            if (result.count == 0) return
            let datas = JSON.parse(result.data).reduce((value, it) => {
                value.push(it.extendObjects)
                return value
            }, [])
            for (let j = 0; j < datas.length; j++) {
                const item = datas[j]
                importFile(sort, item)
            }
            // 查找一个删除一个asr ， 用于后面判断

        })
        return true
    }


    // 6870000000000053    中标通知书
    // 6870000000000054    合同
    // 6870000000000023    招标文件
    // 6870000000000024    投标文件
    // 6870000000000042    中标公示截图
    // 导入共享文件请求
    // %@U2FsdGVkX193pQCoK1lZCdt😀bu9xxJZQeCXNz82l4Ti3DnHrHOiZNyroffirndMTcbvHHyGllPnfTuogTRiwht8ur4BklgMvGYWto9😀7sT3ZhBD+4tC8KtMLkrxW89l3&&0.0.5
    async function importFile(i, item) {
        const asrcode = generateUUID()
        const json = {
            "asrSessionGuid": asrcode,
            "approved": "0",
            "typeId": 0,
            "asrFids": [
                item.asr_fid
            ],
            "asrTable": "system",
            "asrCode": null,
            "busTypeCode": "htzlyj",
        }
        // 导入开始 
        const url = 'http://10.52.119.173:30847/JFileSrv/reactAttach/importFromMyAttach'; // 请求地址
        try {
            const response = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'dbtoken': '0001'
                },
                body: JSON.stringify(json)
            });
            if (!response.ok) {
                throw new Error('网络响应不是OK');
            }
            const result = await response.json();
            const mp = {
                0: '招标文件',
                1: '投标文件',
                2: '开标记录',
                3: '中标公示截图',
                4: '中标通知书',
                5: '合同'
            }
            window._catch_rows.push({
                u_fjlx: mp[i],
                u_fj: asrcode + '@@1',
                u_fjmc: item.asr_name,
                u_scr: item.asr_fillname,
                u_scsj: item.asr_filldt
            });
            console.log('成功收到响应:', result);
        } catch (error) {
            console.error('请求失败:', error);
        }
    }

    function generateUUID() {
        // UUID v4的格式为：xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
        // 其中y位为8、9、A或B

        // 生成随机16进制数的辅助函数
        function randomHex() {
            // 生成0-0xffff的随机数，转换为16进制并补全4位
            return Math.floor((1 + Math.random()) * 0x10000)
                .toString(16)
                .substring(1);
        }

        // 生成y位的值（8-11之间的随机数，16进制为8-b）
        const y = Math.floor(Math.random() * 4) + 8;

        return (
            randomHex() + '-' +
            randomHex() + '-' +
            '4' + randomHex().substring(1) + '-' +  // 第3段以4开头
            y.toString(16) + randomHex().substring(1) + '-' +  // 第4段以y开头
            randomHex() + randomHex()
        );
    }

}, function () {
    console.log('list Ready');
});